package com.mobilesales.android.c2dm;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

public class C2DMReceiver extends C2DMBaseReceiver {

	private static List<NotificationReceiver> receivers = new ArrayList<NotificationReceiver>();
	private static Object sync = new Object();
	public static String senderId = "";

	static void addReceiver(NotificationReceiver receiver) {
		synchronized (sync) {
			if (!receivers.contains(receiver))
				receivers.add(receiver);
		}
	}

	static void removeReceiver(NotificationReceiver receiver) {
		synchronized (sync) {
			if (receivers.contains(receiver))
				receivers.remove(receiver);
		}
	}

	public C2DMReceiver() {
		super(senderId);
	}

	@Override
	public void onUnregistered(Context context) {
		synchronized (sync) {
			for (final NotificationReceiver r : receivers) {
				Handler handler = r.getHandler();
				if (handler != null) {
					handler.post(new Runnable() {
						public void run() {
							r.onUnregistered();
						}
					});
				} else {
					r.onUnregistered();
				}
			}
		}
	}

	@Override
	public void onRegistered(Context context, String registrationId) {
		final String regId = registrationId;
		synchronized (sync) {
			for (final NotificationReceiver r : receivers) {
				Handler handler = r.getHandler();
				if (handler != null) {
					handler.post(new Runnable() {
						public void run() {
							r.onRegistered(regId);
						}
					});
				} else {
					r.onRegistered(registrationId);
				}
			}

		}
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		final String msg = intent.getStringExtra("payload");
		Log.i("C2DMReceiver", "message:" + msg);
		synchronized (sync) {
			for (final NotificationReceiver r : receivers) {
				Handler handler = r.getHandler();
				if (handler != null) {
					handler.post(new Runnable() {
						public void run() {
							r.onMessage(msg);
						}
					});
				} else {
					r.onMessage(msg);
				}
			}

		}
	}

	@Override
	public void onError(Context context, String errorId) {
		final String eid = errorId;
		Log.i("C2DMReceiver", "error:" + errorId);
		synchronized (sync) {
			for (final NotificationReceiver r : receivers) {
				Handler handler = r.getHandler();
				if (handler != null) {
					handler.post(new Runnable() {
						public void run() {
							r.onError(eid);
						}
					});
				} else {
					r.onError(eid);
				}
			}

		}
	}
}
